package com.magist.manage.web.config;

import com.magist.core.auth.AuthUser;
import com.magist.core.entity.CxtHolder;
import com.magist.core.entity.CxtRequest;
import com.magist.core.exception.BusinessException;
import com.magist.core.util.TxtUtil;
import com.magist.manage.enums.UserStatusEnum;
import com.magist.manage.web.dto.UserInfoDto;
import com.magist.manage.web.entity.UserInfo;
import com.magist.manage.web.entity.UserLogin;
import com.magist.manage.web.service.UserInfoService;
import com.magist.manage.web.service.UserLoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017/12/11.
 * 自定义权限匹配和账号密码匹配
 */
public class MyShiroRealm extends AuthorizingRealm {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserLoginService userLoginService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("---------------- 执行 Shiro 权限认证 ----------------------");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal();
//        for (SysRole role : userInfo.getRoleList()) {
//            authorizationInfo.addRole(role.getRole());
//            for (SysPermission p : role.getPermissions()) {
//                authorizationInfo.addStringPermission(p.getPermission());
//            }
//        }
        return authorizationInfo;
    }

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        logger.info("---------------- 执行 Shiro 凭证认证 ----------------------");
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String name = token.getUsername();
        String password = TxtUtil.digest(String.valueOf(token.getPassword()));

        UserLogin userLogin = new UserLogin();
        userLogin.setPassword(password);
        userLogin.setLoginName(name);
        List<UserLogin> userList = userLoginService.find(userLogin);
        if(userList.size()!=1)
            throw new BusinessException("用户不存在");
        UserInfo userInfo = userInfoService.getById(userList.get(0).getId());
        UserInfoDto userInfoDto = new UserInfoDto();
        BeanUtils.copyProperties(userInfo,userInfoDto);
        userInfoDto.setLoginName(name);
        userInfoDto.setPassword(password);
        if(userInfo.getUserStatus().equals(UserStatusEnum.LOCK.getCode()))
            throw new BusinessException("用户已锁定");
        logger.info("---------------- Shiro 凭证认证成功 ----------------------");
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfoDto, //用户
                userInfoDto.getPassword(), //密码
                getName()  //realm name
        );
        AuthUser user = new AuthUser();
        user.setUserId(userInfoDto.getId());
        user.setUserName(userInfo.getUserName());
        CxtRequest cxtR = new CxtRequest();
        cxtR.setRequestId(UUID.randomUUID().toString());
        cxtR.setUser(user);
        CxtHolder.setRequest(cxtR);
        return authenticationInfo;
    }

}
